/**
 * WordPress Spider Monitor - 现代化管理界面JavaScript
 */

// 全局变量
let spiderTrendChart = null;
let spiderActivityChart = null;
let pathsPieChart = null;
let errorBarChart = null;
let heatmapChart = null;
let refreshInterval = null;

// 页面加载完成后初始化
jQuery(document).ready(function($) {
    'use strict';
    
    // 页面卸载时清理
    $(window).on('beforeunload', function() {
        destroyAllCharts();
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
    });
    
    // 初始化付费功能限制
    initPremiumFeatures();
    // 调试：前端识别到的授权状态
    try {
        if (window.wpSpiderMonitor && wpSpiderMonitor.subscription) {
            console.log('[SpiderMonitor] frontend is_premium =', !!wpSpiderMonitor.subscription.is_premium);
        } else {
            console.warn('[SpiderMonitor] frontend wpSpiderMonitor 未定义');
        }
    } catch(e) { /*noop*/ }
    
    // 优化：立即初始化，消除页面切换延迟
    initChartsSafely();
    
    // 优化：立即加载数据，提升用户体验
    loadTodayData();
});

// 初始化付费功能限制
function initPremiumFeatures() {
    const subscription = wpSpiderMonitor.subscription;
    
    // 检查导出功能权限
    if (!subscription.features.export_data) {
        jQuery('#export-data').prop('disabled', true)
            .attr('title', '需要付费订阅')
            .html('📊 导出数据 (付费功能)');
    }
    
    // 检查清理功能权限
    if (!subscription.features.clear_data) {
        jQuery('#clear-data').prop('disabled', true)
            .attr('title', '需要付费订阅')
            .html('🗑️ 清理数据 (付费功能)');
    }
    
    // 检查实时更新权限
    if (!subscription.features.real_time_update) {
        jQuery('#auto-refresh-toggle').prop('disabled', true)
            .attr('title', '需要付费订阅')
            .html('⏱️ 实时更新 (付费功能)');
    }
    
    // 检查高级统计权限
    if (!subscription.features.advanced_stats) {
        jQuery('.advanced-stats').hide();
    }
    
    // 检查多站点权限
    if (!subscription.features.multi_site) {
        jQuery('.multi-site-options').hide();
    }
    
    // 检查API权限
    if (!subscription.features.api_access) {
        jQuery('.api-settings').hide();
    }
}

function initChartsSafely() {
    // 确保所有canvas元素都存在
    const checkCanvas = () => {
        const spiderTrendCanvas = document.getElementById('spider-trend-chart');
        const spiderActivityCanvas = document.getElementById('spider-activity-chart');
        const pathsPieCanvas = document.getElementById('paths-pie-chart');
        
        if (spiderTrendCanvas && spiderActivityCanvas && pathsPieCanvas) {
            console.log('所有canvas元素已就绪，开始初始化图表');
            initCharts();
            bindEvents();
            startAutoRefresh();
            
            // 添加数据状态提示
            jQuery('.chart-container').prepend('<div class="data-status" style="font-size: 12px; color: #666; margin-bottom: 10px;">📊 显示真实蜘蛛访问数据</div>');
        } else {
            console.log('等待canvas元素加载...');
            setTimeout(checkCanvas, 10);
        }
    };
    
    checkCanvas();
}

function destroyAllCharts() {
    safeDestroyChart(spiderTrendChart);
    safeDestroyChart(spiderActivityChart);
    safeDestroyChart(pathsPieChart);
    safeDestroyChart(errorBarChart);
    safeDestroyChart(heatmapChart);
    
    spiderTrendChart = null;
    spiderActivityChart = null;
    pathsPieChart = null;
    
    console.log('所有图表已销毁');
}

function safeDestroyChart(chart) {
    if (chart && typeof chart.destroy === 'function') {
        try {
            chart.destroy();
            console.log('图表销毁成功');
        } catch (error) {
            console.warn('销毁图表时出错:', error);
        }
    }
}

function initCharts() {
    console.log('开始初始化图表...');
    
    // 先销毁现有图表
    destroyAllCharts();
    
    // 初始化蜘蛛趋势图表
    initSpiderTrendChart();
    
    // 初始化蜘蛛活动图表
    initSpiderActivityChart();
    
    // 初始化路径饼图
    initPathsPieChart();

    // 初始化错误柱状图
    initErrorBarChart();

    // 初始化热力图（高级）
    initHeatmapChart();
    // 初始化付费来源占比图（高级）
    initPremiumSourcesChart();
    
    console.log('图表初始化完成');
}

function initSpiderTrendChart() {
    const canvas = document.getElementById('spider-trend-chart');
    if (!canvas) {
        console.log('蜘蛛趋势图表canvas未找到，跳过初始化');
        spiderTrendChart = null;
        return;
    }

    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        spiderTrendChart = null;
        return;
    }

    // 先销毁现有图表
    safeDestroyChart(spiderTrendChart);

    try {
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取2D上下文');
            spiderTrendChart = null;
            return;
        }

        spiderTrendChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [], // 初始为空，等待真实数据加载
                datasets: [] // 空数据集，等待真实数据
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            color: '#64748b',
                            stepSize: 1
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            color: '#64748b',
                            maxRotation: 45
                        }
                    }
                }
            }});
    } catch (error) {
        console.error('初始化蜘蛛趋势图表时出错:', error);
        spiderTrendChart = null;
    }
}

function initSpiderActivityChart() {
    const canvas = document.getElementById('spider-activity-chart');
    if (!canvas) {
        console.log('蜘蛛活动图表canvas未找到，跳过初始化');
        spiderActivityChart = null;
        return;
    }

    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        spiderActivityChart = null;
        return;
    }

    // 先销毁现有图表
    safeDestroyChart(spiderActivityChart);

    try {
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取2D上下文');
            spiderActivityChart = null;
            return;
        }

        spiderActivityChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '总访问次数',
                    data: [],
                    backgroundColor: '#3b82f6',
                    borderColor: '#1d4ed8',
                    borderWidth: 1,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: 'y',
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            color: '#64748b',
                            stepSize: 1
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            color: '#64748b'
                        }
                    }
                }
            }});
    } catch (error) {
        console.error('初始化蜘蛛活动图表时出错:', error);
        spiderActivityChart = null;
    }
}

function initPathsPieChart() {
    const canvas = document.getElementById('paths-pie-chart');
    if (!canvas) {
        console.log('路径饼图canvas未找到，跳过初始化');
        pathsPieChart = null;
        return;
    }

    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        pathsPieChart = null;
        return;
    }

    // 先销毁现有图表
    safeDestroyChart(pathsPieChart);

    try {
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取2D上下文');
            pathsPieChart = null;
            return;
        }

        pathsPieChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['/', '/archives/tag/...', '/category/...', '/page/...', '/post/...'],
                datasets: [{
                    data: [30, 20, 20, 15, 15],
                    backgroundColor: [
                        '#3b82f6',
                        '#60a5fa',
                        '#10b981',
                        '#f59e0b',
                        '#ef4444'
                    ],
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                cutout: '60%'
            }
        });
    } catch (error) {
        console.error('初始化路径饼图时出错:', error);
        pathsPieChart = null;
    }
}

function initErrorBarChart() {
    const canvas = document.getElementById('spider-error-chart');
    if (!canvas) { errorBarChart = null; return; }
    
    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        errorBarChart = null;
        return;
    }
    
    safeDestroyChart(errorBarChart);
    try {
        const ctx = canvas.getContext('2d');
        errorBarChart = new Chart(ctx, {
            type: 'bar',
            data: { labels: [], datasets: [{
                label: '状态码数量', data: [], backgroundColor: '#ef4444', borderColor: '#b91c1c', borderWidth: 1
            }]},
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } }
        });
    } catch (e) { console.warn(e); errorBarChart = null; }
}

function initHeatmapChart() {
    const canvas = document.getElementById('spider-heatmap');
    if (!canvas) { heatmapChart = null; return; }
    
    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        heatmapChart = null;
        return;
    }
    
    safeDestroyChart(heatmapChart);
    try {
        const ctx = canvas.getContext('2d');
        // 使用矩阵柱状来模拟热力效果
        heatmapChart = new Chart(ctx, {
            type: 'matrix',
            data: { datasets: [{ label: '热力', data: [], backgroundColor(ctx){ const v = ctx.raw ? ctx.raw.v : 0; const a = Math.min(0.85, v/20); return `rgba(59,130,246,${a})`;}, width: 16, height: 16, borderWidth: 0 }]},
            options: { plugins: {legend: {display: false}}, scales: { x: { type: 'linear', ticks: {stepSize: 1}}, y: { type: 'category', ticks: {autoSkip: false}} } }
        });
    } catch (e) { console.warn('需要 Chart.js matrix 插件或降级渲染'); heatmapChart = null; }
}

function initPremiumSourcesChart() {
    const canvas = document.getElementById('spider-sources-premium');
    if (!canvas) { return; }
    
    // 检查Chart.js是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载，跳过图表初始化');
        return;
    }
    
    const overlay = document.getElementById('overlay-sources');
    const premium = !!(wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium);
    console.log('[SpiderMonitor] sources premium gate =', premium);
    if (!premium) {
        if (overlay) overlay.style.display = 'flex';
        return;
    } else { if (overlay) overlay.style.display = 'none'; }
    try {
        const ctx = canvas.getContext('2d');
        const chart = new Chart(ctx, { type: 'doughnut', data: { labels: [], datasets: [{ data: [], backgroundColor: ['#3b82f6','#10b981','#f59e0b','#ef4444','#8b5cf6','#06b6d4','#84cc16','#f97316','#6366f1','#14b8a6'] }] }, options: { responsive: true, maintainAspectRatio: false } });
        jQuery.post(wpSpiderMonitor.ajax_url, { action: 'spider_sources_premium', nonce: wpSpiderMonitor.nonce }, function(resp){
            if (resp && resp.success){
                const labels = (resp.data||[]).map(r=>r.spider_name);
                const data = (resp.data||[]).map(r=>parseInt(r.cnt||0));
                chart.data.labels = labels; chart.data.datasets[0].data = data; chart.update('active');
            }
        });
    } catch(e){ console.warn(e); }
}

// 控制热力图遮罩
(function(){
    const overlay = document.getElementById('overlay-heatmap');
    if (!overlay) return;
    const premium = !!(window.wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium);
    console.log('[SpiderMonitor] heatmap premium gate =', premium);
    if (!premium) {
        overlay.style.display = 'flex';
    } else {
        overlay.style.display = 'none';
    }
})();

function updateChartsByTimeRange(timeRange) {
    console.log('更新时间范围:', timeRange);
    
    // 根据时间范围重新加载真实数据
    let days = 1;
    switch(timeRange) {
        case 'today':
            days = 1;
            break;
        case 'week':
            days = 7;
            break;
        case 'month':
            days = 30;
            break;
    }
    
    // 重新加载真实数据
    jQuery.post(wpSpiderMonitor.ajax_url, {
        action: 'spider_get_daily_stats',
        nonce: wpSpiderMonitor.nonce,
        days: days
    })
    .done(function(response) {
        if (response.success) {
            updateChartsWithRealData(response.data);
        }
    })
    .fail(function() {
        console.error('加载图表数据失败');
    });
}

function loadChartData() {
    return jQuery.ajax({
        url: wpSpiderMonitor.ajax_url,
        type: 'POST',
        timeout: 5000, // 5秒超时
        data: {
            action: 'spider_get_daily_stats',
            nonce: wpSpiderMonitor.nonce,
            days: 7
        }
    })
    .done(function(response) {
        if (response.success) {
            // 更新所有图表数据
            updateChartsWithRealData(response.data);
            // 额外加载错误统计
            loadErrorStats();
            // 加载热力图（高级）
            loadHeatmap();
        }
    })
    .fail(function() {
        console.error('加载图表数据失败');
    });
}

function loadErrorStats(){
    jQuery.post(wpSpiderMonitor.ajax_url, { action: 'spider_error_stats', nonce: wpSpiderMonitor.nonce })
        .done(function(resp){ if (resp.success && errorBarChart){ const labels = (resp.data||[]).map(r=>r.response_code); const data = (resp.data||[]).map(r=>parseInt(r.count||0)); errorBarChart.data.labels = labels; errorBarChart.data.datasets[0].data = data; errorBarChart.update('active'); } });
}

function loadHeatmap(){
    const premium = !!(wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium);
    console.log('[SpiderMonitor] loadHeatmap premium =', premium);
    if (!premium) return;
    jQuery.post(wpSpiderMonitor.ajax_url, { action: 'spider_heatmap_24h', nonce: wpSpiderMonitor.nonce })
        .done(function(resp){
            if (!resp || resp.success !== true) {
                const msg = resp && resp.data && resp.data.message ? resp.data.message : '令牌校验失败，请激活PRO版本';
                try{ showNotification(msg, 'error'); }catch(e){ console.warn(msg); }
                return;
            }
            if (!heatmapChart) return;
            const rows = resp.data || [];
            const spiders = [...new Set(rows.map(r=>r.spider_name))];
            const spiderIndex = Object.fromEntries(spiders.map((n,i)=>[n,i]));
            const data = rows.map(r=>({ x: parseInt(r.hour), y: spiders[spiderIndex[r.spider_name]], v: parseInt(r.count) }));
            heatmapChart.data.datasets[0].data = data;
            heatmapChart.options.scales.y.labels = spiders;
            heatmapChart.update('active');
        });
}

function updateChartsWithRealData(data) {
    if (!data || typeof data.hourly_stats === 'undefined') {
        console.warn('未收到有效的hourly_stats，使用0基线渲染');
        const currentHour = new Date().getHours();
        const hours = [];
        for (let hour = 0; hour <= currentHour; hour++) { hours.push(hour); }
        const labels = hours.map(h => `${h.toString().padStart(2, '0')}:00`);
        const zeroData = hours.map(() => 0);
        if (spiderTrendChart) {
            try { spiderTrendChart.data.labels = labels; spiderTrendChart.data.datasets = [{ label: '无数据', data: zeroData, borderColor: '#cbd5e1', backgroundColor: '#cbd5e133', borderWidth: 2, fill: false, tension: 0.1, pointRadius: 0 }]; spiderTrendChart.update('active'); } catch(e){}
        }
        if (spiderActivityChart) {
            try { spiderActivityChart.data.labels = ['无']; spiderActivityChart.data.datasets[0].data = [0]; spiderActivityChart.update('active'); } catch(e){}
        }
        return;
    }

    const hourlyStats = data.hourly_stats;
    const spiderNames = Object.keys(hourlyStats);
    const currentHour = data.current_hour !== undefined ? data.current_hour : new Date().getHours();
    
    if (spiderNames.length === 0) {
        // 构造从0点到当前小时的横线基线，值全部为0
        const hours = [];
        for (let hour = 0; hour <= currentHour; hour++) {
            hours.push(hour);
        }
        const labels = hours.map(h => `${h.toString().padStart(2, '0')}:00`);
        const zeroData = hours.map(() => 0);

        // 更新趋势图为一条0值横线
        if (spiderTrendChart) {
            try {
                spiderTrendChart.data.labels = labels;
                spiderTrendChart.data.datasets = [{
                    label: '无数据',
                    data: zeroData,
                    borderColor: '#cbd5e1',
                    backgroundColor: '#cbd5e133',
                    borderWidth: 2,
                    fill: false,
                    tension: 0.1,
                    pointRadius: 0
                }];
                spiderTrendChart.update('active');
            } catch (e) { console.warn(e); }
        }

        // 更新活动排行图为0
        if (spiderActivityChart) {
            try {
                spiderActivityChart.data.labels = ['无'];
                spiderActivityChart.data.datasets[0].data = [0];
                spiderActivityChart.update('active');
            } catch (e) { console.warn(e); }
        }

        // 路径饼图不变
        return;
    }

    // 显示从0点到当前小时的数据
    const actualHours = [];
    for (let hour = 0; hour <= currentHour; hour++) {
        actualHours.push(hour);
    }
    const labels = actualHours.map(hour => `${hour.toString().padStart(2, '0')}:00`);

    // 定义不同蜘蛛的线型样式
    const lineStyles = [
        { borderDash: [], borderWidth: 3 }, // 实线
        { borderDash: [10, 5], borderWidth: 2 }, // 长虚线
        { borderDash: [5, 5], borderWidth: 2 }, // 短虚线
        { borderDash: [15, 3, 3, 3], borderWidth: 2 }, // 点划线
        { borderDash: [2, 2], borderWidth: 2 }, // 密集虚线
        { borderDash: [20, 5, 5, 5], borderWidth: 2 }, // 空格线
        { borderDash: [8, 4, 2, 4], borderWidth: 2 }, // 混合线
        { borderDash: [12, 6, 2, 6], borderWidth: 2 }  // 复杂线
    ];

    // 定义颜色
    const colors = [
        '#3b82f6', '#ef4444', '#10b981', '#f59e0b', 
        '#8b5cf6', '#06b6d4', '#84cc16', '#f97316'
    ];

    // 构建数据集
    const datasets = spiderNames.map((spiderName, index) => {
        const style = lineStyles[index % lineStyles.length];
        const color = colors[index % colors.length];
        
        // 根据实际有数据的小时填充数据
        const spiderData = hourlyStats[spiderName] || {};
        const data = actualHours.map(hour => spiderData[hour] || 0);

        return {
            label: spiderName,
            data: data,
            borderColor: color,
            backgroundColor: `${color}20`,
            borderWidth: style.borderWidth,
            borderDash: style.borderDash,
            fill: false,
            tension: 0.1,
            pointBackgroundColor: color,
            pointBorderColor: '#ffffff',
            pointBorderWidth: 2,
            pointRadius: 3,
            pointHoverRadius: 5
        };
    });

    // 安全更新图表的函数
    function safeUpdateChart(chartInstance, updateFn) {
        if (!chartInstance || typeof chartInstance.update !== 'function') {
            return false;
        }
        
        try {
            updateFn();
            chartInstance.update('active');
            return true;
        } catch (error) {
            console.error('更新图表时出错:', error);
            return false;
        }
    }

    // 更新蜘蛛趋势图表
    const spiderTrendCanvas = document.getElementById('spider-trend-chart');
    if (spiderTrendChart && spiderTrendCanvas && spiderTrendCanvas.parentNode) {
        safeUpdateChart(spiderTrendChart, function() {
            spiderTrendChart.data.labels = labels;
            spiderTrendChart.data.datasets = datasets;
        });
    } else {
        console.log('蜘蛛趋势图表不存在或已被移除，跳过更新');
    }

    // 更新蜘蛛活动图表
    const spiderActivityCanvas = document.getElementById('spider-activity-chart');
    if (spiderActivityChart && spiderActivityCanvas && spiderActivityCanvas.parentNode) {
        safeUpdateChart(spiderActivityChart, function() {
            spiderActivityChart.data.labels = spiderNames;
            spiderActivityChart.data.datasets[0].data = spiderNames.map(name => {
                const spiderData = hourlyStats[name] || {};
                return Object.values(spiderData).reduce((sum, count) => sum + count, 0);
            });
        });
    } else {
        console.log('蜘蛛活动图表不存在或已被移除，跳过更新');
    }

    // 更新路径饼图
    const pathsPieCanvas = document.getElementById('paths-pie-chart');
    if (pathsPieChart && pathsPieCanvas && pathsPieCanvas.parentNode && data.paths_data) {
        safeUpdateChart(pathsPieChart, function() {
            const paths = data.paths_data;
            const labels = Object.keys(paths);
            const values = Object.values(paths);
            
            if (labels.length > 0 && values.length > 0) {
                pathsPieChart.data.labels = labels;
                pathsPieChart.data.datasets[0].data = values;
            }
        });
    } else {
        console.log('路径饼图不存在或已被移除，跳过更新');
    }

    // 更新概览统计
    const totalVisits = spiderNames.reduce((sum, name) => {
        const spiderData = hourlyStats[name] || {};
        return sum + Object.values(spiderData).reduce((s, c) => s + c, 0);
    }, 0);

    const totalSpiders = spiderNames.length;
    const totalPages = data.unique_pages || 0;

    jQuery('.stat-value').eq(0).text(formatNumber(totalVisits));
    jQuery('.stat-value').eq(1).text(formatNumber(totalSpiders));
    jQuery('.stat-value').eq(2).text(formatNumber(totalPages));

    // 更新蜘蛛列表
    if (data.spiders) {
        updateSpidersList(data.spiders);
    }
}

function showSpiderDetails(spiderName) {
    const modal = jQuery('#spider-modal');
    const content = jQuery('#spider-modal-content');
    
    content.html('<div class="loading"></div> 加载中...');
    modal.addClass('show');

    jQuery.post(wpSpiderMonitor.ajax_url, {
        action: 'spider_get_spider_details',
        nonce: wpSpiderMonitor.nonce,
        spider_name: spiderName
    })
    .done(function(response) {
        if (response.success) {
            const data = response.data;
            content.html(`
                <div class="spider-details-content">
                    <div class="spider-header">
                        <div class="spider-avatar ${getSpiderAvatarClass(spiderName)}">
                            ${getSpiderInitials(spiderName)}
                        </div>
                        <div>
                            <h3>${spiderName}</h3>
                            <p>最后访问: ${data.last_visit || '无'}</p>
                        </div>
                    </div>
                    <div class="spider-stats-grid">
                        <div class="stat-item">
                            <div class="stat-label">访问次数</div>
                            <div class="stat-value">${formatNumber(data.visit_count)}</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-label">访问页面</div>
                            <div class="stat-value">${formatNumber(data.unique_pages)}</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-label">平均响应时间</div>
                            <div class="stat-value">${data.avg_response_time || 0}ms</div>
                        </div>
                    </div>
                    <div class="spider-actions">
                        <button class="btn btn-primary" onclick="loadSpiderUrls('${spiderName}')">
                            查看访问页面
                        </button>
                    </div>
                </div>
            `);
        } else {
            content.html(`
                <div class="empty-state">
                    <div class="empty-state-icon">❌</div>
                    <h3 class="empty-state-title">加载失败</h3>
                    <p class="empty-state-description">${response.data || '未知错误'}</p>
                </div>
            `);
        }
    })
    .fail(function() {
        content.html(`
            <div class="empty-state">
                <div class="empty-state-icon">❌</div>
                <h3 class="empty-state-title">网络错误</h3>
                <p class="empty-state-description">请检查网络连接后重试</p>
            </div>
        `);
    });
}

function loadSpiderUrls(spiderName) {
    const content = jQuery('#spider-modal-content');
    content.html('<div class="loading"></div> 加载中...');

    jQuery.post(wpSpiderMonitor.ajax_url, {
        action: 'spider_get_spider_urls',
        nonce: wpSpiderMonitor.nonce,
        spider_name: spiderName,
        date: new Date().toISOString().split('T')[0]
    })
    .done(function(response) {
        if (response.success) {
            const urls = response.data.urls || [];
            let html = '<div class="spider-urls-list">';
            
            if (urls.length === 0) {
                html += '<div class="empty-state"><p>暂无访问记录</p></div>';
            } else {
                urls.forEach(function(url) {
                    html += `
                        <div class="url-item">
                            <div class="url-info">
                                <div class="url-path">${url.url}</div>
                                <div class="url-meta">
                                    访问时间: ${formatTime(url.visit_time)} | 
                                    响应时间: ${url.response_time}ms | 
                                    状态码: ${url.response_code}
                                </div>
                            </div>
                        </div>
                    `;
                });
            }
            
            html += '</div>';
            content.html(html);
        } else {
            content.html(renderPremiumNoticeHtml('令牌校验失败，请激活PRO版本', wpSpiderMonitor.ajax_url.replace('admin-ajax.php','admin.php?page=spider-license')));
        }
    })
    .fail(function() {
        content.html('<div class="empty-state"><p>加载失败</p></div>');
    });
}

function startAutoRefresh() {
    // 付费订阅启用时才自动刷新
    if (wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium) {
        refreshInterval = setInterval(function() {
            loadTodayData();
        }, 60000); // 改为1分钟刷新，减少频率
    }
}

function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

function formatNumber(num) {
    return new Intl.NumberFormat('zh-CN').format(num);
}

function formatTime(timeString) {
    if (!timeString) return '无';
    const date = new Date(timeString);
    return date.toLocaleTimeString('zh-CN');
}

function getSpiderAvatarClass(spiderName) {
    const name = spiderName.toLowerCase();
    if (name.includes('google')) return 'google';
    if (name.includes('bing')) return 'bing';
    if (name.includes('baidu')) return 'baidu';
    return 'other';
}

function getSpiderInitials(spiderName) {
    return spiderName.substring(0, 2).toUpperCase();
}

function showNotification(message, type = 'info') {
    const notification = jQuery(`
        <div class="spider-notification spider-notification-${type}" style="
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 8px;
            padding: 12px 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            border-left: 4px solid #007cba;
            z-index: 9999;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            max-width: 300px;
            font-size: 14px;
        ">
            ${message}
        </div>
    `);

    jQuery('body').append(notification);
    
    // 显示动画 - 立即显示
    notification.css('transform', 'translateX(0)');
    
    // 自动隐藏 - 减少延迟
    setTimeout(() => {
        notification.css('transform', 'translateX(100%)');
        setTimeout(() => notification.remove(), 100);
    }, 2000);
}

function saveThemePreference(theme) {
    const button = jQuery('#interface_theme');
    const originalText = button.parent().find('.description').text();
    
    button.parent().find('.description').text('保存中...');

    jQuery.post(wpSpiderMonitor.ajax_url, {
        action: 'save_theme_preference',
        nonce: wpSpiderMonitor.nonce,
        theme: theme
    })
    .done(function(response) {
        if (response.success) {
            // 仅在设置页面显示主题通知
            if (jQuery('#wp-spider-monitor-settings').length) {
                showNotification('主题已更新！页面将刷新以应用新主题。', 'success');
            }
            setTimeout(() => location.reload(), 500);
        } else {
            showNotification('主题更新失败：' + (response.data || '未知错误'), 'error');
        }
    })
    .fail(function() {
        showNotification('网络错误，请重试', 'error');
    })
    .always(function() {
        button.parent().find('.description').text(originalText);
    });
}

function closeSpiderModal() {
    jQuery('#spider-modal').removeClass('show');
}

// 添加通知样式
const notificationStyles = `
    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        background: white;
        border-radius: 12px;
        padding: 16px 20px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        border-left: 4px solid #3b82f6;
        z-index: 10000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 400px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
    }
    
    .notification.show {
        transform: translateX(0);
    }
    
    .notification-success {
        border-left-color: #10b981;
    }
    
    .notification-error {
        border-left-color: #ef4444;
    }
    
    .notification-close {
        background: none;
        border: none;
        font-size: 18px;
        color: #64748b;
        cursor: pointer;
        padding: 0;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .notification-close:hover {
        color: #1e293b;
    }
`;

// 添加样式到页面
const styleSheet = document.createElement('style');
styleSheet.textContent = notificationStyles;
document.head.appendChild(styleSheet);

    // 绑定事件
    function bindEvents() {
        // 创建数据表
        jQuery(document).on('click', '#create-tables', createTables);
        
        // 导出数据
        jQuery(document).on('click', '#export-data', exportData);
        
        // 清理数据
        jQuery(document).on('click', '#clear-data', clearData);
        
        // 刷新图表
        jQuery(document).on('click', '#refresh-chart', refreshChart);
        
        // 刷新蜘蛛列表
        jQuery(document).on('click', '#refresh-spiders', refreshSpiders);
        
        // 蜘蛛项目点击
        jQuery(document).on('click', '.spider-item', function() {
            const spiderName = jQuery(this).data('spider');
            if (wpSpiderMonitor.subscription.is_premium || confirm('此功能需要高级订阅。是否继续查看？')) {
                showSpiderDetails(spiderName);
            }
        });
        
        // 时间选择器
        jQuery(document).on('change', '.time-selector', function() {
            const timeRange = jQuery(this).val();
            
            // 简化验证：直接检查全局激活状态
            if (timeRange === 'week' || timeRange === 'month') {
                if (!window.wpSpiderMonitor || !window.wpSpiderMonitor.subscription || !window.wpSpiderMonitor.subscription.is_premium) {
                    // 显示激活提示
                    const $selectedOption = jQuery(this).find('option:selected');
                    if ($selectedOption.hasClass('premium-option')) {
                        alert('7天和30天数据查看需要激活PRO版本');
                        // 重置为今天
                        jQuery(this).val('today');
                        return;
                    }
                }
            }
            
            updateChartsByTimeRange(timeRange);
        });
        
        // 主题切换
        jQuery(document).on('change', '#interface_theme', function() {
            const theme = jQuery(this).val();
            if (theme === 'pro' && !wpSpiderMonitor.subscription.is_premium) {
                showNotification('Pro主题需要高级订阅', 'error');
                jQuery(this).val('default');
                return;
            }
            saveThemePreference(theme);
        });
        
        // 主题预览
        jQuery(document).on('click', '.theme-preview', function() {
            const theme = jQuery(this).data('theme');
            if (theme === 'pro' && !wpSpiderMonitor.subscription.is_premium) {
                showNotification('Pro主题需要高级订阅', 'error');
                return;
            }
            jQuery('#interface_theme').val(theme).trigger('change');
        });
        
        // 探索按钮
        jQuery(document).on('click', '.explore-btn', function() {
            window.location.href = wpSpiderMonitor.ajaxUrl + '?page=wp-spider-monitor-settings';
        });
    }

    // 创建数据表
    function createTables() {
        if (!confirm('确定要创建数据库表吗？')) {
            return;
        }

        const button = jQuery('#create-tables');
        const originalText = button.html();
        
        button.html('<span class="loading"></span> 创建中...').prop('disabled', true);

        jQuery.post(wpSpiderMonitor.ajax_url, {
            action: 'spider_create_tables',
            nonce: wpSpiderMonitor.nonce
        })
        .done(function(response) {
            if (response.success) {
                showNotification('数据库表创建成功！页面将刷新。', 'success');
                setTimeout(() => location.reload(), 800);
            } else {
                showNotification('创建失败：' + (response.data || '未知错误'), 'error');
            }
        })
        .fail(function() {
            showNotification('网络错误，请重试', 'error');
        })
        .always(function() {
            button.html(originalText).prop('disabled', false);
        });
    }

    // 导出数据
    function exportData() {
        const subscription = wpSpiderMonitor.subscription;
        
        if (!subscription.features.export_data) {
            showNotification('导出功能需要付费订阅。请前往许可证管理页面升级订阅。', 'error');
            return;
        }
        
        const button = jQuery('#export-data');
        const originalText = button.html();
        
        button.html('<span class="loading"></span> 导出中...').prop('disabled', true);

        jQuery.post(wpSpiderMonitor.ajax_url, {
            action: 'spider_export_stats',
            nonce: wpSpiderMonitor.nonce
        })
        .done(function(response) {
            if (response.success) {
                showNotification('数据导出成功！', 'success');
                // 触发下载
                const link = document.createElement('a');
                link.href = response.data.download_url;
                link.download = response.data.filename;
                link.click();
            } else {
                showNotification('导出失败：' + (response.data || '未知错误'), 'error');
            }
        })
        .fail(function() {
            showNotification('网络错误，请重试', 'error');
        })
        .always(function() {
            button.html(originalText).prop('disabled', false);
        });
    }

    // 清理数据
    function clearData() {
        const subscription = wpSpiderMonitor.subscription;
        
        if (!subscription.features.clear_data) {
            showNotification('清理功能需要付费订阅。请前往许可证管理页面升级订阅。', 'error');
            return;
        }
        
        if (!confirm('确定要清理30天前的数据吗？此操作不可撤销！')) {
            return;
        }

        const button = jQuery('#clear-data');
        const originalText = button.html();
        
        button.html('<span class="loading"></span> 清理中...').prop('disabled', true);

        jQuery.post(wpSpiderMonitor.ajax_url, {
            action: 'spider_clear_old_visits',
            nonce: wpSpiderMonitor.nonce
        })
        .done(function(response) {
            if (response.success) {
                showNotification(`数据清理完成！删除了 ${response.data.deleted_visits} 条访问记录和 ${response.data.deleted_stats} 条统计记录。`, 'success');
                loadTodayData();
            } else {
                showNotification('清理失败：' + (response.data || '未知错误'), 'error');
            }
        })
        .fail(function() {
            showNotification('网络错误，请重试', 'error');
        })
        .always(function() {
            button.html(originalText).prop('disabled', false);
        });
    }

    // 刷新图表
    function refreshChart() {
        const button = jQuery('#refresh-chart');
        const originalText = button.html();
        
        button.html('<span class="loading"></span> 刷新中...').prop('disabled', true);

        loadChartData().always(function() {
            button.html(originalText).prop('disabled', false);
        });
    }

    // 刷新蜘蛛列表
    function refreshSpiders() {
        const button = jQuery('#refresh-spiders');
        const originalText = button.html();
        
        button.html('<span class="loading"></span> 刷新中...').prop('disabled', true);

        loadTodayData().always(function() {
            button.html(originalText).prop('disabled', false);
        });
    }

    // 加载今日数据
    function loadTodayData() {
        return jQuery.ajax({
            url: wpSpiderMonitor.ajax_url,
            type: 'POST',
            timeout: 5000, // 5秒超时
            data: {
                action: 'spider_get_daily_stats',
                nonce: wpSpiderMonitor.nonce,
                days: 1
            }
        })
        .done(function(response) {
            if (response.success) {
                updateOverviewStats(response.data);
                updateChartsWithRealData(response.data);
                
                // 显示数据更新时间
                const now = new Date();
                const timeString = now.toLocaleTimeString();
                console.log(`真实数据已加载，更新时间: ${timeString}`);
                
                // 添加数据提示
                if (response.data.total_visits === 0) {
                    showNotification('暂无蜘蛛访问记录，请等待真实数据', 'info');
                } else {
                    showNotification(`已加载 ${response.data.total_visits} 条真实访问记录`, 'success');
                }
            }
        })
        .fail(function() {
            console.error('加载今日数据失败');
            showNotification('加载真实数据失败，请检查数据库连接', 'error');
        });
    }

    // 更新概览统计
    function updateOverviewStats(data) {
        // 安全处理数据，避免NaN
        const totalVisits = data.total_visits || 0;
        const totalSpiders = data.total_spiders || 0;
        const totalPages = data.total_pages || 0;

        jQuery('.stat-value').eq(0).text(formatNumber(totalVisits));
        jQuery('.stat-value').eq(1).text(formatNumber(totalSpiders));
        jQuery('.stat-value').eq(2).text(formatNumber(totalPages));

        // 更新状态指示器
        updateStatusIndicators({
            total_visits: totalVisits,
            total_spiders: totalSpiders,
            total_pages: totalPages
        });
    }

    // 更新状态指示器
    function updateStatusIndicators(data) {
        const indicators = jQuery('.status-indicator');
        
        // 监控状态
        indicators.eq(0).removeClass('active inactive')
            .addClass(data.total_visits > 0 ? 'active' : 'inactive')
            .find('.status-dot').removeClass('active inactive')
            .addClass(data.total_visits > 0 ? 'active' : 'inactive');
        
        // 蜘蛛活动状态
        indicators.eq(1).removeClass('active inactive')
            .addClass(data.total_spiders > 0 ? 'active' : 'inactive')
            .find('.status-dot').removeClass('active inactive')
            .addClass(data.total_spiders > 0 ? 'active' : 'inactive');
        
        // 页面访问状态
        indicators.eq(2).removeClass('active inactive')
            .addClass(data.total_pages > 0 ? 'active' : 'inactive')
            .find('.status-dot').removeClass('active inactive')
            .addClass(data.total_pages > 0 ? 'active' : 'inactive');
    }

    // 更新蜘蛛列表
    function updateSpidersList(spiders) {
        const container = jQuery('.spider-list');
        
        if (!spiders || spiders.length === 0) {
            container.html(`
                <div class="no-data-message">
                    <p>今日暂无蜘蛛访问记录</p>
                </div>
            `);
            return;
        }

        // 只显示前3个最活跃的蜘蛛
        const topSpiders = spiders.slice(0, 3);
        let html = '';
        
        topSpiders.forEach(function(spider) {
            html += `
                <div class="spider-item">
                    <div class="spider-name">${spider.spider_name}</div>
                    <div class="spider-count">${formatNumber(spider.visit_count)}</div>
                </div>
            `;
        });

        container.html(html);
    }

// 简单的占位提示（令牌失效或未授权）
function renderPremiumNoticeHtml(message, url){
    const msg = message || '令牌校验失败，请激活PRO版本';
    const link = url || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php','admin.php?page=spider-license') : '#');
    return '<div class="premium-notice">' +
        '<div class="premium-restriction">' +
        '<span class="premium-icon">🔒</span>' +
        '<span class="premium-text">' + msg + '</span>' +
        '<a class="premium-link" href="' + link + '">立即激活</a>' +
        '</div>' +
        '</div>';
}

// 添加底部标志到插件内容区域
function addFooterLogo() {
    // 检查是否已经存在底部标志
    if (jQuery('.spider-footer').length > 0) {
        return;
    }
    
    // 创建底部标志HTML
    const footerHTML = `
        <div class="spider-footer">
            <div class="spider-footer-content">
                <a href="https://zibovip.top" target="_blank" class="spider-footer-logo">
                    <span class="logo-text">小Z</span>
                </a>
            </div>
        </div>
    `;
    
    // 优先添加到插件内容区域
    const pluginContainers = [
        '.spider-content-area',
        '.spa-container .spider-content-area',
        '#spider-content-area',
        '.wp-admin .wrap'
    ];
    
    let added = false;
    for (let selector of pluginContainers) {
        const container = jQuery(selector);
        if (container.length > 0) {
            container.append(footerHTML);
            added = true;
            console.log('底部标志已添加到插件内容区域:', selector);
            break;
        }
    }
    
    // 如果没找到插件容器，不添加
    if (!added) {
        console.log('未找到合适的插件内容区域，跳过添加底部标志');
    }
}

// 页面加载完成后添加底部标志
jQuery(document).ready(function($) {
    // 延迟添加，确保页面完全加载
    setTimeout(addFooterLogo, 100);
});